package com.csxy.systemmanager.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.csxy.systemmanager.dao.MenuDao;
import com.csxy.systemmanager.dao.UserDao;
import com.csxy.systemmanager.entity.LoginUser;
import com.csxy.systemmanager.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    //注入dao层
    @Autowired
    private UserDao userDao;

    @Autowired
    private MenuDao menuDao;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //声明查询条件Wrapper
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        //用username作为条件
        queryWrapper.eq(User::getUserName, username);
        //查询用户
        User user = userDao.selectOne(queryWrapper);
        //判断是否查出来
        if(ObjectUtils.isNull(user)){
            throw new UsernameNotFoundException("用户名或者密码错误");
        }
        //根据用户的id查出对于的权限列表
        List<String> perms = menuDao.selectPermsByUserId(user.getId());

        //封装成loginUser返回
        return new LoginUser(user,perms);
    }
}
